package xyz.jcat.biz.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.jcat.auth.token.AccessTokenUtils;
import xyz.jcat.auth.token.UserTokenDto;
import xyz.jcat.biz.admin.domain.dao.IUserRoleDao;
import xyz.jcat.biz.admin.domain.dto.UserRoleBindDto;
import xyz.jcat.biz.admin.domain.po.UserPo;
import xyz.jcat.biz.admin.domain.po.UserRolePo;
import xyz.jcat.biz.admin.service.IUserRoleService;
import xyz.jcat.biz.admin.service.IUserService;
import xyz.jcat.common.util.CollectionUtils;
import xyz.jcat.common.web.RespCodeMsg;
import xyz.jcat.mybatis.ServiceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 * @author yueyue
 * auto on 2022-04-28 13:41:47
 */
@Service
public class UserRoleService extends ServiceImpl<IUserRoleDao, UserRolePo> implements IUserRoleService {

    @Autowired
    private IUserService userService;

    @Override
    public List<Long> getRoleIdsByUserId(Long userId) {
        return dao.getRoleIdsByUserId(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindUserRole(UserRoleBindDto userRoleBindDto) {
        Long userId = userRoleBindDto.getUserId();
        UserPo user = userService.getById(userId);
        RespCodeMsg.DATA_NOT_FOUND.isNull(user);
        deleteByUserId(userId);
        Set<Long> roleIds = userRoleBindDto.getRoleIds();
        if(CollectionUtils.isEmpty(roleIds))
            return;

        List<UserRolePo> list = roleIds.stream().map(roleId -> {
            UserRolePo userRolePo = new UserRolePo();
            userRolePo.setUserId(userId);
            userRolePo.setRoleId(roleId);
            return userRolePo;
        }).collect(Collectors.toList());
        insertBatch(list);
        //修改用户token缓存的角色信息
        AccessTokenUtils.updateUserToken(new UserTokenDto(userId, new ArrayList<>(roleIds)));
    }

    private void deleteByUserId(Long userId) {
        LambdaQueryWrapper<UserRolePo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserRolePo::getUserId, userId);
        dao.delete(lambdaQueryWrapper);
    }
}
